#include "ControlLogic.h"

#include <As/Http/HttpResponse.h>
#include <As/Logic/Session.h>

namespace As {

ControlLogic::ControlLogic(QObject *parent):
    AbstractHttpLogic(parent)
{
}

void ControlLogic::request(As::HttpRequest req) {
    QString action = req.m_headerMap["action"];
    QString param = req.m_headerMap["param"];
    QString login = req.m_headerMap["login"];
    QString sessionId = req.m_headerMap["session-id"];
    qDebug() << sessionId << login << action << param;
    if (sessionId.isEmpty() || action.isEmpty() || login.isEmpty()) {
        emit response(HttpResponse(req.m_socket, "", "400 Bad Request"));
    }
    else {
        if (action == "hello") {
            if (m_sessionMap.find(sessionId) == m_sessionMap.end()) {
                AbstractHttpLogic * session = new Session(sessionId, this);
                connect(session, SIGNAL(response(As::HttpResponse)),
                        this, SLOT(sessionResponse(As::HttpResponse)));
                m_sessionMap[sessionId] = session;
                session->request(req);
            }
            else {
                emit response(HttpResponse(req.m_socket, "", "400 Bad Request"));
            }
        }
        else {
            if (m_sessionMap.find(sessionId) == m_sessionMap.end()) {
                HttpResponse resp(req.m_socket, "", "401 Unauthorized");
            }
            else {
                m_sessionMap[sessionId]->request(req);
            }
        }

    }
}

void ControlLogic::sessionResponse(As::HttpResponse resp) {
    emit response(resp);
}

void ControlLogic::deleteSession(const QString &sid) {
    QMap<QString, AbstractHttpLogic*>::iterator it = m_sessionMap.find(sid);
    if (it != m_sessionMap.end()) {
        delete it.value();
        m_sessionMap.erase(it);
        qDebug() << "session" << sid << "deleted";
    }
}

}
